import React, { useState, useRef } from "react";  // 添加 useRef
import PropTypes from 'prop-types';
import { message, Spin, Button } from "antd";
import { AudioOutlined } from '@ant-design/icons';
import IconCube from "../../assets/cube.svg";
import IconSend from "../../assets/send.svg";
import { useGlobalContext } from "../../context/GlobalContext";
import "./index.css";
import { getApiUrl } from "../../config/api";

export const InputBar = ({ model }) => {
  const [loading, setLoading] = useState(false);
  const [inputText, setInputText] = useState("");
  const [isRecording, setIsRecording] = useState(false);
  const { setChatContent, setQuestion, user } = useGlobalContext();

  // 添加录音状态的 ref
  const isRecordingRef = useRef(false);
  const recognitionRef = useRef(null);
  const lastUpdateRef = useRef(0);

  const handleVoiceInput = async () => {
    // 检查浏览器兼容性
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SpeechRecognition) {
      message.error('您的浏览器不支持语音识别功能，请使用 Chrome 浏览器');
      return;
    }

    // 如果正在录音，则停止
    if (isRecording) {
      isRecordingRef.current = false;
      if (recognitionRef.current) {
        recognitionRef.current.stop();
      }
      return;
    }

    try {
      // 先请求麦克风权限
      await navigator.mediaDevices.getUserMedia({ audio: true });
      
      const recognition = new SpeechRecognition();
      recognitionRef.current = recognition;
      
      recognition.lang = 'zh-CN';
      recognition.continuous = true;
      recognition.interimResults = true;
      recognition.maxAlternatives = 1;

      recognition.onstart = () => {
        console.log('语音识别开始');
        isRecordingRef.current = true;
        setIsRecording(true);
        message.info('开始录音，请说话...');
      };

      recognition.onresult = (event) => {
        // 添加节流
        const now = Date.now();
        if (now - lastUpdateRef.current < 100) return;
        lastUpdateRef.current = now;

        console.log('语音识别结果:', event.results);
        let finalTranscript = '';
        let interimTranscript = '';

        for (let i = 0; i < event.results.length; i++) {
          const result = event.results[i];
          if (result.isFinal) {
            finalTranscript += result[0].transcript;
          } else {
            interimTranscript += result[0].transcript;
          }
        }

        const fullTranscript = finalTranscript + interimTranscript;
        console.log('识别文本:', fullTranscript);
        if (fullTranscript) {
          setInputText(fullTranscript);
        }
      };

      recognition.onerror = (event) => {
        console.error('语音识别错误:', {
          error: event.error,
          message: event.message,
          timestamp: new Date().toISOString(),
          browserInfo: navigator.userAgent
        });

        let errorMessage = '语音识别失败';
        switch (event.error) {
          case 'network':
            errorMessage = '网络连接失败，请检查网络或尝试使用VPN';
            break;
          case 'not-allowed':
            errorMessage = '请允许使用麦克风权限并刷新页面';
            break;
          case 'no-speech':
            errorMessage = '没有检测到语音，请重试';
            break;
          case 'aborted':
            errorMessage = '语音识别已取消';
            break;
          default:
            errorMessage = `语音识别失败: ${event.error}`;
        }
        
        message.error(errorMessage);
        isRecordingRef.current = false;
        setIsRecording(false);
      };

      recognition.onend = () => {
        console.log('语音识别结束');
        if (isRecordingRef.current) {
          // 如果还在录音状态，则重新开始
          try {
            recognition.start();
          } catch (error) {
            console.error('重新启动语音识别失败:', error);
            isRecordingRef.current = false;
            setIsRecording(false);
          }
        } else {
          setIsRecording(false);
          recognitionRef.current = null;
          // 语音识别完成后自动发送
          if (inputText.trim()) {
            handleSubmit();
          }
          message.success('语音识别完成');
        }
      };

      recognition.start();
    } catch (error) {
      console.error('启动语音识别失败:', error);
      message.error('启动语音识别失败，请确保已授权麦克风权限');
      isRecordingRef.current = false;
      setIsRecording(false);
    }
  };

  // 组件卸载时清理
  React.useEffect(() => {
    return () => {
      if (recognitionRef.current) {
        recognitionRef.current.stop();
      }
    };
  }, []);

  const handleSubmit = async () => {
    if (loading) return;
    if (!inputText.trim()) {
      message.error("请输入内容");
      return;
    }

    try {
      setLoading(true);
      
      const response = await fetch(getApiUrl('/api/chat/query'), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${user.token}`,
        },
        body: JSON.stringify({ 
          prompt: inputText,
          model: model  // 使用传入的模型参数
        }),
      });

      const resData = await response.json();

      if (resData.ok) {
        setQuestion(inputText);
        // 更新界面显示
        setChatContent((prevContent) => [
          ...prevContent,
          { role: "user", content: inputText },
          { role: "assistant", content: resData.data },
        ]);
        setInputText("");

        // 触发历史记录刷新
        const event = new CustomEvent('refreshHistory');
        window.dispatchEvent(event);
      }
    } catch (error) {
      console.error("发送消息失败:", error);
      message.error("发送失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    setInputText(e.target.value);
  };

  // 添加键盘事件处理函数
  const handleKeyPress = (e) => {
    if (e.key === "Enter") {
      e.preventDefault();
      handleSubmit();
    }
  };

  return (
    <div className="input-bar">
      <img className="input-bar-icon" src={IconCube} alt="AI魔方" />
      <input
        className="input-bar-input"
        type="text"
        placeholder="请输入"
        value={inputText}
        onChange={handleChange}
        onKeyPress={handleKeyPress}
      />
      <Button
        icon={<AudioOutlined />}
        onClick={handleVoiceInput}
        type={isRecording ? 'primary' : 'default'}
        className="input-bar-voice"
      />
      <button className="input-bar-send" onClick={handleSubmit}>
        {loading && <Spin size="small" />}
        {!loading && (
          <div className="input-bar-send-icon">
            <img
              className="input-bar-send-icon-img"
              src={IconSend}
              alt="发送"
            />
          </div>
        )}
      </button>
    </div>
  );
};

// 添加 PropTypes 验证
InputBar.propTypes = {
  model: PropTypes.string
};

// 添加默认值
InputBar.defaultProps = {
  model: 'doubao'
};
